<template>
  <div class="query-form">
    <el-form :model="queryParams" label-width="70px" :inline="true" ref="queryFormRef">
      <!-- 订单编号 -->
      <el-form-item label="订单编号" prop="orderNo">
        <el-input v-model="queryParams.orderNo" class="!w-50" placeholder="请输入订单编号" clearable />
      </el-form-item>

      <!-- 企业名称 -->
      <el-form-item label="企业名称" prop="enterpriseName">
        <el-input v-model="queryParams.enterpriseName" class="!w-50" placeholder="请输入企业名称" clearable />
      </el-form-item>

      <!-- 机构名称 -->
      <el-form-item label="机构名称" prop="organizationName">
        <el-input v-model="queryParams.organizationName" class="!w-50" placeholder="请输入机构名称" clearable />
      </el-form-item>

      <!-- 订单状态 -->
      <!-- <el-form-item label="订单状态" prop="orderState">
        <el-select v-model="queryParams.orderState" placeholder="请选择订单状态" class="!w-45" clearable>
          <el-option v-for="(item, index) in orderStateOptions" :key="index" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item> -->

      <!-- 申请时间 -->
      <el-form-item label="申请时间" prop="applyTimeRange">
        <el-date-picker v-model="queryParams.applyTimeRange" class="!w-70" type="daterange" range-separator="至"
          start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD" />
      </el-form-item>

      <!-- 授信时间 -->
      <el-form-item label="授信时间" prop="creditTimeRange">
        <el-date-picker v-model="queryParams.creditTimeRange" class="!w-70" type="daterange" range-separator="至"
          start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD" />
      </el-form-item>

      <!-- 用信时间 -->
      <el-form-item label="用信时间" prop="useCreditTimeRange">
        <el-date-picker v-model="queryParams.useCreditTimeRange" class="!w-70" type="daterange" range-separator="至"
          start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD" />
      </el-form-item>

      <!-- 查询和重置按钮 -->
      <el-form-item>
        <el-button type="primary" @click="handleQuery">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 查询结果展示区域（示例） -->
    <div>
      <el-tabs v-model="queryParams.orderState" @tab-change="tabChange" type="card">
        <el-tab-pane v-for="item in orderStateOptions" :key="item.value" :label="item.label" :name="item.value">
          <!-- All orders content will be placed here -->
        </el-tab-pane>
      </el-tabs>
      <el-table :data="tableData" border header-cell-class-name="table-header">
        <!-- 订单编号 -->
        <el-table-column prop="orderNo" label="订单编号" width="100" align="center"></el-table-column>

        <!-- 机构名称（企业名称） -->
        <el-table-column prop="financingMatch.enterpriseName" label="企业名称" width="100" align="center"></el-table-column>

        <!-- 统一信用代码（这里假设没有直接对应的字段，可以根据实际情况添加或忽略） -->
        <!-- 如果有相应的字段，请替换为正确的prop值 -->
        <el-table-column prop="financingMatch.creditCode" label="统一信用代码" width="110" align="center"></el-table-column>

        <!-- 金融产品（产品名称） -->
        <el-table-column prop="productName" label="金融产品" width="100" align="center"></el-table-column>
        <el-table-column prop="organizationName" label="金融机构" width="100" align="center"></el-table-column>

        <!-- 金融机构（机构名称）已经在上面列出 -->

        <!-- 派单模式（这里假设没有直接对应的字段，可以根据实际情况添加或忽略） -->
        <!-- 如果有相应的字段，请替换为正确的prop值 -->
        <el-table-column prop="financingMatch.matchType" label="派单模式" width="80"
          :formatter="(row) => transformDict('matchType', row.financingMatch.matchType)"
          align="center"></el-table-column>

        <!-- 订单状态 -->
        <el-table-column prop="orderState" label="订单状态" width="80" align="center"
          :formatter="formatOrderState"></el-table-column>

        <!-- 申请时间（创建时间） -->
        <el-table-column prop="createTime" label="申请时间" width="100" align="center"></el-table-column>

        <!-- 授信额度 -->
        <el-table-column prop="creditAmount" label="授信额度" width="80" align="center"></el-table-column>

        <!-- 授信时间 -->
        <el-table-column prop="creditTime" label="授信时间" width="100" align="center"></el-table-column>

        <!-- 用信额度 -->
        <el-table-column prop="loanAmount" label="用信额度" width="80" align="center"></el-table-column>

        <!-- 用信时间 -->
        <el-table-column prop="loanTime" label="用信时间" width="100" align="center"></el-table-column>

        <!-- 还款状态 -->
        <el-table-column prop="paymentState" label="还款状态" :formatter="formatRepayState" width="80"
          align="center"></el-table-column>

        <!-- 融资顾问 -->
        <el-table-column prop="financialAdvisor" label="融资顾问" width="80" align="center"></el-table-column>

        <!-- 客户经理 -->
        <el-table-column prop="managerName" label="客户经理" width="80" align="center"></el-table-column>

        <!-- 操作 -->
        <el-table-column label="操作" fixed="right" width="150" align="center">
          <template #default="{ row }">

            <el-button size="small" @click="navTo('orderDetailPage', { orderNo: row.orderNo, applyNo: row.applyId })"
              type="primary">详情</el-button>
            <el-dropdown trigger="click" @command="handleDropdownCommand" class="ml-3">
              <el-button size="small" :icon="ArrowDown" type="primary">更多</el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item v-if="row.orderState == '2'"
                    :command="{ row, type: 'shouxin' }">添加授信</el-dropdown-item>
                  <!-- <el-dropdown-item v-if="row.orderState == '2'" :command="{row,type:'jinrong'}">修改金融产品</el-dropdown-item>
                  <el-dropdown-item v-if="row.orderState == '2'" :command="{row,type:'kehu'}">修改客户经理</el-dropdown-item> -->
                  <el-dropdown-item v-if="row.orderState == '4'"
                    :command="{ row, type: 'yongxin' }">添加用信</el-dropdown-item>
                  <el-dropdown-item v-if="row.orderState == '5'"
                    :command="{ row, type: 'payBack' }">添加还款</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>

            <!-- 可根据需要添加更多操作按钮 -->
          </template>
        </el-table-column>
      </el-table>

      <el-pagination class="mt-5" v-model:current-page="queryParams.pageNum" :total="total" background
        @current-change="getList" layout="prev, pager, next" />

      <!-- 授信记录 -->
      <el-dialog class="!p-4 " width="600" v-model="dialogCredit" title="添加授信记录">
        <div>
          <el-form :model="formCredit" label-width="auto" :rules="rulesCredit">
            <el-form-item label="授信结果" prop="creditState">
              <el-radio-group v-model="formCredit.creditState">
                <el-radio value="1">授信通过</el-radio>
                <el-radio value="0">授信拒绝</el-radio>
              </el-radio-group>
            </el-form-item>
            <!-- 授信金额 -->
            <el-form-item label="授信机构" prop="organizationId">
              <el-cascader v-model="formCredit.organizationId" :options="organizationOptions"
                @change="handleOrganizationOptionChange" />
            </el-form-item>

            <el-form-item label="授信金额" prop="creditAmount">
              <el-input v-model="formCredit.creditAmount" placeholder="请输入授信金额">
                <template #suffix>
                  <span>万元</span>
                </template>
              </el-input>
            </el-form-item>

            <!-- 授信时间 -->
            <el-form-item label="授信日期" prop="creditTime">
              <el-date-picker format="YYYY/MM/DD" value-format="YYYY-MM-DD" type="datetime" placeholder="选择日期时间"
                v-model="formCredit.creditTime"></el-date-picker>
            </el-form-item>

            <!-- 授信利率 -->
            <el-form-item label="授信利率" prop="realRate">
              <el-input-number v-model="formCredit.realRate" :precision="2" :step="0.01" :min="0"
                placeholder="请输入授信利率"></el-input-number>
            </el-form-item>

            <!-- 还款方式 -->
            <el-form-item label="还款方式" prop="paymentType">
              <el-select v-model="formCredit.paymentType" placeholder="请选择还款方式">
                <el-option v-for="(item, index) in repaymentTypeOptions" :key="index" :label="item.label"
                  :value="item.value" />

              </el-select>
            </el-form-item>

            <!-- 授信期限 -->
            <el-form-item label="授信期限" prop="creditPeriod">
              <el-input v-model="formCredit.creditPeriod" :min="1" placeholder="请输入授信期限">
                <template #prepend>月</template>
              </el-input>
            </el-form-item>

            <!-- 备注 -->
            <el-form-item label="备注" prop="remark">
              <el-input type="textarea" v-model="formCredit.remark" placeholder="请输入备注"></el-input>
            </el-form-item>

            <!-- 授信状态 -->
          </el-form>
        </div>
        <template #footer>
          <div>
            <el-button type="primary" @click="handleSubmitCredit">提 交</el-button>
            <el-button @click="dialogCredit = false">取 消</el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 用信记录 -->
      <el-dialog class="!p-4" width="600px" v-model="dialogLoan" title="添加用信记录">
        <div>
          <el-form :model="formLoan" label-width="auto" :rules="rulesCredit">

            <el-form-item label="用信金额" prop="loanAmount">
              <el-input v-model="formLoan.loanAmount" placeholder="请输入用信金额">
                <template #suffix>
                  <span>万元</span>
                </template>
              </el-input>
            </el-form-item>

            <!-- 授信时间 -->
            <el-form-item label="用信时间" prop="loanTime">
              <el-date-picker format="YYYY/MM/DD" value-format="YYYY-MM-DD" type="datetime" placeholder="选择日期时间"
                v-model="formLoan.loanTime"></el-date-picker>
            </el-form-item>

            <!-- 授信期限 -->
            <el-form-item label="用信期限" prop="loanPeriod">
              <el-input v-model="formLoan.loanPeriod" :min="1" placeholder="请输入授信期限">
                <template #prepend>月</template>
              </el-input>
            </el-form-item>

            <!-- 授信利率 -->
            <el-form-item label="用信利率" prop="loanRate">
              <el-input-number v-model="formLoan.loanRate" :precision="2" :step="0.01" :min="0"
                placeholder="请输入授信利率"></el-input-number>
            </el-form-item>

            <!-- 还款方式 -->
            <el-form-item label="还款方式" prop="paymentType">
              <el-select v-model="formLoan.paymentType" placeholder="请选择还款方式">
                <el-option v-for="(item, index) in repaymentTypeOptions" :key="index" :label="item.label"
                  :value="item.value" />

              </el-select>
            </el-form-item>

            <!-- 备注 -->
            <el-form-item label="备注" prop="remark">
              <el-input type="textarea" v-model="formLoan.remark" placeholder="请输入备注"></el-input>
            </el-form-item>

            <!-- 授信状态 -->
          </el-form>
        </div>
        <template #footer>
          <div>
            <el-button type="primary" @click="handleSubmitLoan">提 交</el-button>
            <el-button @click="dialogLoan = false">取 消</el-button>
          </div>
        </template>
      </el-dialog>

      <el-dialog v-model="dialogPayBack" width="600" title="添加还款记录">
        <el-form :model="formPayBack">
          <el-form-item label="还款类型">
            <el-select v-model="formPayBack.repaymentType" placeholder="请选择还款类型">
              <el-option v-for="(item, index) in paymentTypeOptions" :key="index" :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="还款金额">
            <el-input v-model="formPayBack.repaymentAmount" placeholder="请输入还款金额">
              <template #suffix>
                <span>万元</span>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="还款日期">
            <el-date-picker format="YYYY/MM/DD" value-format="YYYY-MM-DD" v-model="formPayBack.repaymentTime"
              type="date" placeholder="Pick a day" :size="size" />
          </el-form-item>
          <el-form-item label="备注">
            <el-input type="textarea" v-model="formPayBack.remark" placeholder="请输入备注"></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <div>
            <el-button type="primary" @click="handleSubmitRepayment">提 交</el-button>
            <el-button @click="dialogPayBack = false">取 消</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { addCredit, addLoan, addRepayment, getOrderList } from '@/api/order'
import { getOrganizationTreeList } from '@/api/organization'
import { useDict, transformDict } from '@/hooks/dict'
import { ArrowDown } from '@element-plus/icons-vue'
import { useNavTo } from '@/hooks/navTo'
const { navTo } = useNavTo()
const { orderState: orderStateOptions, repaymentType: repaymentTypeOptions, paymentType: paymentTypeOptions } = useDict('orderState', 'repaymentState', 'repaymentType', 'paymentType', 'matchType')

const tableData = ref([])
const total = ref(0)
const selectedRow = ref({})
const formCredit = reactive({
  creditState: '1', // 默认授信通过
  creditAmount: 0,
  creditTime: '',
  realRate: 0,
  paymentType: '',
  creditPeriod: 0,
  remark: '',
  organizationId: '',
  organizationName: '',
  refuseReason: ''
})
const formPayBack = reactive({
  repaymentAmount: 0,
  repaymentTime: '',
  orderNo: '',
  repaymentType: '',
  machNo: '',
  remark: ''
})
const formLoan = reactive({
  loanAmount: 0,
  loanTime: '',
  loanRate: 0,
  paymentType: '',
  loanPeriod: 0,
  remark: '',
})
const organizationOptions = ref([])
onMounted(() => {
  // Fetch initial data or perform setup actions
  getList()

  getOrganizationTreeList().then(response => {
    // Handle the response data
    console.log('Organization Tree List:', response)
    organizationOptions.value = response.data
  })
})

function tabChange(tab) {
  getList()
}

const dialogCredit = ref(false)
const dialogPayBack = ref(false)
const dialogLoan = ref(false)

function getList() {

  getOrderList(queryParams).then(response => {
    // Handle the response data
    tableData.value = response.rows
    total.value = response.total
  })
}
function formatOrderState(row) {
  return transformDict('orderState', row.orderState)
}
function handleOrganizationOptionChange(value) {
  // 处理组织机构选择变化
}

function formatRepayState(row) {
  return transformDict('repaymentState', row.paymentState)
}

// 提交用信记录
function handleSubmitLoan(value) {
  // 处理组织机构选择变化
  const row = unref(selectedRow);
  const form = cloneDeep(formLoan)
  form.machNo = row.machId
  form.orderNo = row.orderNo
  form.organizationName = row.organizationName
  addLoan(form).then(res => {
    if (res.code == 200) {
      ElMessage.success("用信记录添加成功");
      getList()
      dialogCredit.value = false;
      resetLoanForm()
    }
  })
}

// 提交还款记录
function handleSubmitRepayment(value) {
  // 处理组织机构选择变化
  const row = unref(selectedRow);
  const form = cloneDeep(formPayBack)
  form.machNo = row.machId
  form.orderNo = row.orderNo
  addRepayment(form).then(res => {
    if (res.code == 200) {
      ElMessage.success("还款记录添加成功");
      getList()
      dialogPayBack.value = false;
      resetRepayForm()
    }
  })
}
function resetLoanForm() {
  formLoan.loanAmount = 0
  formLoan.loanTime = ''
  formLoan.loanRate = 0
  formLoan.paymentType = ''
  formLoan.loanPeriod = 0
  formLoan.remark = ''
}
function resetRepayForm() {
  formLoan.loanAmount = 0
  formLoan.loanTime = ''
  formLoan.loanRate = 0
  formLoan.paymentType = ''
  formLoan.loanPeriod = 0
  formLoan.remark = ''
}

function resetCreditForm() {
  // 假设 formLoan 已经存在
  formLoan.creditState = '1'; // 默认授信通过
  formLoan.creditAmount = 0;
  formLoan.creditTime = '';
  formLoan.realRate = 0;
  formLoan.paymentType = '';
  formLoan.creditPeriod = 0;
  formLoan.remark = '';
  formLoan.organizationId = '';
  formLoan.organizationName = '';
  formLoan.refuseReason = '';
}

function handleDropdownCommand(command) {
  // 处理下拉菜单的命令
  console.log('Dropdown command:', command)
  // 根据 command 执行相应的操作
  selectedRow.value = command.row
  switch (command.type) {
    case 'shouxin':
      // 添加授信逻辑
      dialogCredit.value = true
      console.log('添加授信')
      break
    case 'udpProduct':
      // 修改金融产品逻辑
      console.log('修改金融产品')
      break
    case 'udpManager':
      // 修改客户经理逻辑
      console.log('修改客户经理')
      break
    case 'yongxin':
      // 添加用信逻辑
      dialogLoan.value = true
      console.log('添加用信')
      break
    case 'payBack':
      // 添加还款逻辑
      dialogPayBack.value = true
      console.log('添加还款')
      break
  }

}
import { cloneDeep } from 'lodash-es'
import { formatter } from 'element-plus'
// 提交授信记录
function handleSubmitCredit() {
  const row = unref(selectedRow);
  const form = cloneDeep(formCredit)
  form.organizationId = row.organizationId
  form.machNo = row.machId
  form.orderNo = row.orderNo
  form.organizationName = row.organizationName
  addCredit(form).then(res => {
    if (res.code == 200) {
      ElMessage.success("授信记录添加成功");
      dialogCredit.value = false;
      resetCreditForm()
      getList()
    }
  })
}


// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  orderNo: '',
  enterpriseName: '',
  organizationName: '',
  orderState: '0',
  applyTimeRange: [], // [startTime, endTime]
  creditTimeRange: [],
  useCreditTimeRange: []
})

// 表单引用（用于重置）
const queryFormRef = ref(null)


// 查询处理
const handleQuery = () => {
  console.log('查询参数:', { ...queryParams })
  // 这里可以调用 API 发起查询请求
  getList()
}

// 重置处理
const handleReset = () => {
  queryFormRef.value?.resetFields()
  // 注意：reactive 数据需要手动重置 date picker 的值（因为 resetFields 不会重置数组）
  queryParams.applyTimeRange = []
  queryParams.creditTimeRange = []
  queryParams.useCreditTimeRange = []
  getList()
}
</script>

<style scoped lang="scss">
.query-form {
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
}

.result {
  margin-top: 20px;
  padding: 10px;
  background-color: #fff;
  border: 1px solid #ddd;
  border-radius: 4px;
}
</style>
